var qs = require('querystring');
var formidable = require('formidable');
var exec = require('child_process').exec;
var fs = require('fs');

function start(response, request)
{
    console.log("Request handler 'start' was called.");
    var body =
	'<html>'+
        '<head>'+
        '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />'+
        '</head>'+
        '<body>'+
        '<form action="/upload?playerId=15" enctype="multipart/form-data" method="post">'+
        '<input type="file" name="upload" multiple="multiple">'+
        '<input type="submit" value="Upload file" />'+
        '</form>'+
        '</body>'+
    '</html>';
	
    response.writeHead(200, {'Content-Type' : 'text/html'})
    response.write(body);
    response.end();
}

function upload(response, request)
{
    console.info('upload start');
    var tmpDir = './tmp';
    if( !fs.existsSync(tmpDir) )
    {
        fs.mkdirSync(tmpDir);
        console.info('create tmp dir success');
    }
    var form = new formidable.IncomingForm();
    form.uploadDir = tmpDir;
	var url = request.url;
	var playerId = request.url.substring(request.url.indexOf("=")+1);
    form.parse(request, function(error, fields, files)
    {
        var uploadDir = './images/';
        if( !fs.existsSync(uploadDir) )
        {
            fs.mkdirSync(uploadDir);
            console.info('create upload dir success');
        }
        console.info('upload file tmp path:',files.upload.path);
        fs.renameSync(files.upload.path,uploadDir + playerId + '.jpg');
        response.end();
    })
}

function get(response, request)
{
    console.log('request handler \'show\' was called...') ;
    var playerId = request.url.substring(request.url.indexOf("=")+1);
	if(playerId == 0)
    {
		fs.readFile("./images/test.jpg", "binary", function(error, file)
        {
			if (error)
            {
				response.writeHead(500, {"Content-Type": "text/plain"});
				response.write(error + "\n");
				response.end();
			}
            else
            {
				response.writeHead(200, {"Content-Type": "image/jpg"});
				response.write(file, "binary");
				response.end();
			}
		});
    }
    else
    {
		fs.readFile("./images/"+playerId+".jpg", "binary", function(error, file)
        {
			if (error)
			{
				response.writeHead(500, {"Content-Type": "text/plain"});
				response.write(error + "\n");
				response.end();
			}
			else
			{
				response.writeHead(200, {"Content-Type": "image/jpg"});
				response.write(file, "binary");
				response.end();
			}
		});	
   }		
}

exports.start = start;
exports.upload = upload;
exports.get = get;

